import { FlexDiv } from "@/components/FOF/SelectInput";
import { PageWrapper } from "@/components/PageWrapper";
import { Title } from "@/components/Title";
import { Button, Input, Select, Table, Tabs } from "antd";
import { useEffect, useState } from "react";
import styled from "styled-components";
import styles from "./index.less";
import { getFundList, getHoldDetail, getPage } from "./services";
import * as _ from "lodash";

const { TabPane } = Tabs;
let timer = null;

const FundPage = () => {
  const [fundCode, setFundCode] = useState({});
  const [tableData, setTableData] = useState({});
  const [fundList, setFundList] = useState([]);
  const [tabList, setTabList] = useState([]);
  const [curTab, setCurTab] = useState("");
  const [curVal, setCurVal] = useState();
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (curTab && tableData[curTab]) {
      handleCalcVal();
    }
  }, [tableData[curTab]]);

  useEffect(() => {
    clearInterval(timer);
    handleResolvePage(tabList.filter((v) => v?.value === curTab)[0]);
    timer = setInterval(() => {
      //   console.log(tabList.filter((v) => v.value === curTab)[0], curTab);

      handleResolvePage(tabList.filter((v) => v?.value === curTab)[0]);
    }, 15000);
  }, [curTab]);

  const onSelectFund = (e) => {
    setFundCode(e);
    if (e) {
      handleResolvePage(e);
    }
  };

  // 查询基金
  const handleQueryFundList = (e) => {
    if (!e) return;
    getFundList({ fundCode: e }).then((res) => {
      setFundList(res);
    });
  };

  // 根据提取的股票代码来获取持仓明细变动
  const handleQueryStockDetail = (s, e: any, result: any, flag?: boolean) => {
    setLoading(true);
    getHoldDetail({ stockCode: s }).then((res) => {
      setLoading(false);
      const i = tabList.findIndex((v) => v.value === e.value);
      setTabList((state) => {
        return i > -1 ? state : [...state, e];
      });
      setCurTab(e.value);
      setTableData((state) => {
        return {
          ...state,
          [e.value]: res.data.diff.map((v, i) => {
            v.f9 = result.rate[i];
            v.f10 = result.total[i];
            return v;
          }),
        };
      });
    });
  };

  console.log(tabList);
  

  // 处理页面中的数据
  const handleResolvePage = (e) => {
    // const stockBox = document.getElementById("hold-stock");
    if (!e?.value && !fundCode?.value) return;
    getPage({ fundCode: e?.value || fundCode?.value }).then((res) => {
      if (res) {
        // stockBox.innerHTML = res.html;
        if (e?.value) {
          handleQueryStockDetail(res.data, e, res);
        } else {
          handleQueryStockDetail(res.data, fundCode, res, true);
        }
      }
    });
  };

  //   console.log(tabList);

  const columns = [
    {
      title: "股票代码",
      dataIndex: "f12",
      key: "f12",
    },
    {
      title: "股票名称",
      dataIndex: "f14",
      key: "f14",
    },
    {
      title: "最新价",
      dataIndex: "f2",
      key: "f2",
    },
    {
      title: "涨跌幅",
      dataIndex: "f3",
      key: "f3",
      render: (text) => (
        <div style={{ color: text > 0 ? "red" : "green" }}>{text}</div>
      ),
    },
    {
      title: "占净值比例",
      dataIndex: "f9",
      key: "f9",
    },
    // {
    //   title: "持仓市值（万元）",
    //   dataIndex: "f10",
    //   key: "f10",
    // },
  ];

  // 计算当前基金估值
  //   以各个股票当前的占比和涨跌幅加权计算
  const handleCalcVal = () => {
    const data = tableData[curTab];
    let total = -1;
    let base = 0;
    let totalValue = 0;
    for (let i = 0; i < data.length; i++) {
      total += data[i].f3 * Number(data[i].f9.slice(0, -1));
      base += Number(data[i].f9.slice(0, -1));
      totalValue += Number(data[i].f10?.replaceAll(",", ""));
    }
    console.log(totalValue);
    setCurVal(total / base);
  };
  console.log(fundList);
  
  return (
    <PageWrapper narrow minWidth="1068px">
      <Title style={{ marginLeft: 16, marginBottom: 12 }}>基金页面</Title>
      <FlexDiv>
        <Select
          onSearch={_.debounce(handleQueryFundList, 500)}
          onChange={onSelectFund}
          value={fundCode}
          showSearch
          allowClear
          labelInValue
          style={{ width: 236 }}
          filterOption={false}
        >
          {fundList?.length > 0
            ? fundList?.map((v) => (
                <Select.Option value={v.CODE} key={v.CODE}>
                  {v.NAME}
                </Select.Option>
              ))
            : null}
        </Select>
      </FlexDiv>
      <FlexDiv style={{ marginTop: 16, marginBottom: 16 }}>
        {/* <Button
          type="primary"
          onClick={handleResolvePage}
          style={{ marginRight: 24 }}
        >
          获取基金持仓股票
        </Button> */}
        {/* <Button type="default" onClick={handleQueryStockDetail}>
          获取基金持仓股票涨跌明细
        </Button> */}
      </FlexDiv>

      <iframe
        className={styles.myIframe}
        id={fundCode + "iframe"}
        key={fundCode + "iframe"}
        style={{ position: "relative", zIndex: 3 }}
        border="none"
        src={`http://fundf10.eastmoney.com/ccmx_${fundCode}.html`}
      />
      <div>基金持仓股票:</div>
      <div id="hold-stock"></div>
      <div>
        当前估值：
        <span style={{ color: curVal < 0 ? "green" : "red" }}>{curVal}</span>
      </div>
      <Tabs className={styles.cusTab} activeKey={curTab} onChange={setCurTab}>
        {tabList &&
          tabList?.map((v) => (
            <TabPane tab={v.label} key={v.value}>
              <Table
                columns={columns}
                rowKey={(r) => r.f12}
                pagination={false}
                dataSource={tableData[curTab]}
                loading={loading}
              />
            </TabPane>
          ))}
      </Tabs>
    </PageWrapper>
  );
};

export default FundPage;
